import sys

import cv2
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QAbstractItemView

from database_tool.storage_resources import DatabaseConnector
from display_image.comic_show import ComicDisplay
from ui.main_win import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        # 获取信息
        self.cd = None  # 显示章节漫画
        self.chapter_info = None    # 章节信息
        self.tableWidget = None
        self.listWidget = None  # 目录控件
        self.dc = DatabaseConnector()
        self.comics_list = self.dc.get_all_comics()
        print("所有漫画信息>>>>:", self.comics_list)

        self.setupUi(self)
        self.label_2.setScaledContents(True)  # 自适应
        self._translate = QtCore.QCoreApplication.translate
        self.label_2.setMaximumSize(170, 16777215)

        self.load_comic_catalog()

    # 记载漫画目录
    def load_comic_catalog(self):
        self.listWidget = QtWidgets.QListWidget(self.widget_3)
        self.listWidget.setStyleSheet("#listWidget{\n"
                                      "border:0;}")
        self.listWidget.setAutoScrollMargin(12)
        self.listWidget.setGridSize(QtCore.QSize(0, 51))
        self.listWidget.setModelColumn(0)
        self.listWidget.setObjectName("listWidget")
        self.verticalLayout_5.addWidget(self.listWidget)
        self.listWidget.setCurrentRow(-1)
        # 加载信息
        for row, comics_info in enumerate(self.comics_list):
            item = QtWidgets.QListWidgetItem()
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            font = QtGui.QFont()
            font.setPointSize(12)
            item.setFont(font)
            self.listWidget.addItem(item)
            item = self.listWidget.item(row)
            item.setText(self._translate("MainWindow", comics_info[1]))
        self.listWidget.itemDoubleClicked.connect(self.double_clicked_load_info)  # 双击信号连接槽
        __sortingEnabled = self.listWidget.isSortingEnabled()
        self.listWidget.setSortingEnabled(False)
        self.listWidget.setSortingEnabled(__sortingEnabled)
        self.verticalLayout_5.addWidget(self.listWidget)

    # 获取当前目录id
    def double_clicked_load_info(self):
        self.current_row = self.listWidget.currentRow()
        self.load_directory(self.comics_list[self.current_row])

    # 加载单个漫画信息
    def load_directory(self, comics):
        # 显示封面
        cover_img = cv2.imread(comics[6])
        cover_img = cv2.resize(cover_img, (192, 209))
        cover_img = cv2.cvtColor(cover_img, cv2.COLOR_BGR2RGB)
        cover_img = QtGui.QImage(cover_img.data, cover_img.shape[1], cover_img.shape[0], QtGui.QImage.Format_RGB888)
        self.label_2.setPixmap(QPixmap.fromImage(cover_img))
        # 显示漫画名
        self.label_12.setText(comics[1])
        # 显示作者
        author = ""
        if len(comics[4]) <= 10:
            author += comics[4][0:10]
        elif 10 < len(comics[4]) <= 20:
            author += comics[4][0:10] + "\n" + comics[4][10:20]
        else:
            author += comics[4][0:10] + "\n" + comics[4][10:20] + "..."
        self.label_14.setText(author)
        # 显示标签
        self.label_8.setText(comics[3])
        # 显示类型
        self.label_10.setText(comics[2])
        # 显示介绍
        self.textEdit.setText(comics[5])
        if self.tableWidget:
            self.tableWidget.hide()
        dc = DatabaseConnector()
        # 获取章节信息
        self.chapter_info = dc.get_comics_chapter(comics[0])
        self.load_chapters_number(self.chapter_info)

    # 加载漫画章数
    def load_chapters_number(self, chapter_info):
        chapter_pages = len(chapter_info)  # 章节页数
        # 取出四的倍数作为函数
        row = chapter_pages // 4
        # 不足四个自己到四个
        if chapter_pages % 4 == 0:
            for i in range(chapter_pages % 4):
                chapter_info.append(" ")
        self.tableWidget = QtWidgets.QTableWidget(self.widget_2)
        self.tableWidget.setStyleSheet("#tableWidget{\n"
                                       "border:0;}")
        self.tableWidget.setLocale(QtCore.QLocale(QtCore.QLocale.Chinese, QtCore.QLocale.China))
        self.tableWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.tableWidget.setAutoScrollMargin(10)
        self.tableWidget.setAlternatingRowColors(True)
        self.tableWidget.setShowGrid(False)
        self.tableWidget.horizontalHeader().setVisible(False)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(185)
        self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.verticalHeader().setDefaultSectionSize(59)
        self.verticalLayout_4.addWidget(self.tableWidget)
        self.tableWidget.setRowCount(row + 1)
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setObjectName("tableWidget")
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(13)
        item.setFont(font)
        brush = QtGui.QBrush(QtGui.QColor(81, 81, 81))
        brush.setStyle(QtCore.Qt.NoBrush)
        item.setForeground(brush)
        item.setFlags(
            QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled | QtCore.Qt.ItemIsUserCheckable)
        self.tableWidget.setItem(0, 0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setFlags(
            QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled | QtCore.Qt.ItemIsUserCheckable)
        self.tableWidget.setItem(0, 1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setFlags(
            QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled | QtCore.Qt.ItemIsUserCheckable)
        self.tableWidget.setItem(0, 2, item)
        item = QtWidgets.QTableWidgetItem()
        item.setFlags(
            QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled | QtCore.Qt.ItemIsUserCheckable)
        self.tableWidget.setItem(0, 3, item)
        self.tableWidget.setSortingEnabled(False)
        item = self.tableWidget.verticalHeaderItem(0)
        item.setText(self._translate("MainWindow", "新建行"))
        item = self.tableWidget.verticalHeaderItem(1)
        item.setText(self._translate("MainWindow", "新建行"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(self._translate("MainWindow", "新建列"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(self._translate("MainWindow", "新建列"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(self._translate("MainWindow", "新建列"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(self._translate("MainWindow", "新建列"))
        item = self.tableWidget.item(0, 0)
        item.setText(self._translate("MainWindow", "   漫画目录："))
        for i in range(0, row):
            index = i + 1
            item = QtWidgets.QTableWidgetItem()
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            font = QtGui.QFont()
            font.setPointSize(10)
            item.setFont(font)
            self.tableWidget.setItem(index, 0, item)

            item = QtWidgets.QTableWidgetItem()
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            font = QtGui.QFont()
            font.setPointSize(10)
            item.setFont(font)
            self.tableWidget.setItem(index, 1, item)

            item = QtWidgets.QTableWidgetItem()
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            font = QtGui.QFont()
            font.setPointSize(10)
            item.setFont(font)
            self.tableWidget.setItem(index, 2, item)

            item = QtWidgets.QTableWidgetItem()
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            font = QtGui.QFont()
            font.setPointSize(10)
            item.setFont(font)
            self.tableWidget.setItem(index, 3, item)
            # 显示数据
            item = self.tableWidget.item(index, 0)
            item.setText(self._translate("MainWindow", chapter_info[i * 4 + 0][0]))
            item = self.tableWidget.item(index, 1)
            item.setText(self._translate("MainWindow", chapter_info[i * 4 + 1][0]))
            item = self.tableWidget.item(index, 2)
            item.setText(self._translate("MainWindow", chapter_info[i * 4 + 2][0]))
            item = self.tableWidget.item(index, 3)
            item.setText(self._translate("MainWindow", chapter_info[i * 4 + 3][0]))

        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置不可编辑
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        self.tableWidget.itemDoubleClicked.connect(self.show_comics_chapter)
        self.tableWidget.setSortingEnabled(__sortingEnabled)

    # 显示章节
    def show_comics_chapter(self, item=None):
        if item is None:
            return
        else:
            row = item.row()  # 获取行数
            col = item.column()  # 获取列数 注意是column而不是col哦
            index = (row - 1) * 4 + col    # 获索引
            if self.chapter_info[index]:
                self.cd = ComicDisplay(self.chapter_info[index][0], self.chapter_info[index][1], self.chapter_info, index)
                self.cd.show()
            else:
                return


if __name__ == "__main__":
    app = QApplication(sys.argv)
    m = MainWindow()
    m.show()
    sys.exit(app.exec_())  # 程序关闭时退出进程
